package leetcode.editor.cn;

//编写一个函数来查找字符串数组中的最长公共前缀。 
//
// 如果不存在公共前缀，返回空字符串 ""。 
//
// 
//
// 示例 1： 
//
// 
//输入：strs = ["flower","flow","flight"]
//输出："fl"
// 
//
// 示例 2： 
//
// 
//输入：strs = ["dog","racecar","car"]
//输出：""
//解释：输入不存在公共前缀。 
//
// 
//
// 提示： 
//
// 
// 1 <= strs.length <= 200 
// 0 <= strs[i].length <= 200 
// strs[i] 仅由小写英文字母组成 
// 
// Related Topics 字符串 
// 👍 1803 👎 0

import java.util.ArrayList;
import java.util.List;

public class LongestCommonPrefix {
    public static void main(String[] args) {
        Solution solution = new LongestCommonPrefix().new Solution();

//        String s = solution.longestCommonPrefix(new String[]{"flower", "flow", "flight"});
//        System.out.println(s);

        String s2 = solution.longestCommonPrefix(new String[]{"cir", "car"});
        System.out.println(s2);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String longestCommonPrefix(String[] strs) {

            if (strs.length == 0) {
                return "";
            }
            if (strs.length == 1) {
                return strs[0];
            }
            String prefix = strs[0];

            String[] prefixSp = prefix.split("");
            StringBuilder prefixBuild = new StringBuilder();
            boolean hanext = true;
            for (int i = 0; i < prefixSp.length; i++) {
                if (!hanext) {
                    continue;
                }
                String p = prefixSp[i];
                List<Boolean> flgs = new ArrayList<Boolean>();

                for (String str : strs) {

                    String[] split = str.split("");


                    if (split.length <= i) {
                        flgs.add(false);
                        hanext = false;
                        break;

                    } else {
                        boolean equals = p.equals(split[i]);
                        if (equals) {
                            flgs.add(p.equals(split[i]));
                        } else {
                            hanext = false;
                            break;
                        }
                    }


                }
                if (flgs.size() == strs.length && !flgs.stream().filter(a -> !a.booleanValue()).findFirst().isPresent()) {
                    prefixBuild.append(p);
                }
            }


            return prefixBuild.toString();
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
